package com.lyl.servicestatistics.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyl.commonutils.DateUtils;
import com.lyl.commonutils.R;
import com.lyl.commonutils.redis.RedisConstants;
import com.lyl.commonutils.redis.RedisUtils;
import com.lyl.servicestatistics.cloudclient.OrderClient;
import com.lyl.servicestatistics.cloudclient.UcenterClient;
import com.lyl.servicestatistics.entity.StatisticsDaily;
import com.lyl.servicestatistics.entity.excel.DailyExcel;
import com.lyl.servicestatistics.mapper.StatisticsDailyMapper;
import com.lyl.servicestatistics.service.StatisticsDailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-06-29
 */
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl<StatisticsDailyMapper, StatisticsDaily> implements StatisticsDailyService {

    @Autowired
    StatisticsDailyMapper dailyMapper;

    @Autowired
    UcenterClient ucenterClient;
    @Autowired
    OrderClient orderClient;

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public void createStatisticsByDay(String day) {
        QueryWrapper<StatisticsDaily> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("date_calculated",day);
        StatisticsDaily statisticsDaily= this.baseMapper.selectOne(queryWrapper);


        if(statisticsDaily==null) {
            // 新插入数据
            statisticsDaily = new StatisticsDaily();
        }


        statisticsDaily.setDateCalculated(day);//1.当天日期
        RedisUtils.setDataBase(redisTemplate,4);

     // 这几个值到redis中读取
        statisticsDaily.setLoginNum(redisTemplate.opsForValue().get(day+"/"+RedisConstants.LOGIN_NUM)==null?0:Long.parseLong(redisTemplate.opsForValue().get(day+"/"+ RedisConstants.LOGIN_NUM)));
        statisticsDaily.setVideoViewNum(redisTemplate.opsForValue().get(day+"/"+RedisConstants.VIDEO_VIEW_NUM)==null?0:Long.parseLong(redisTemplate.opsForValue().get(day+"/"+RedisConstants.VIDEO_VIEW_NUM)));
        statisticsDaily.setWebAccessNum(redisTemplate.opsForValue().get(day+"/"+RedisConstants.WEB_ACCESS_NUM)==null?0:Long.parseLong(redisTemplate.opsForValue().get(day+"/"+RedisConstants.WEB_ACCESS_NUM)));


        // 远程调用其他模块读取
        R ucenterR=ucenterClient.getCountByDay(day);
        System.out.println(ucenterR);
        statisticsDaily.setRegisterNum(new Long((Integer)ucenterR.getData().get("count")));

        R orderR=orderClient.getOrderCountByDay(day);
        System.out.println(orderR);
        statisticsDaily.setCoursePriceSum((Double)orderR.getData().get("count"));



        System.out.println("统计信息:"+ statisticsDaily);

        if(statisticsDaily.getId()!=null)
             this.baseMapper.updateById(statisticsDaily);
        else
             this.baseMapper.insert(statisticsDaily);
    }

    @Override
    public Map<String, Object> getDataByBetween(String statrTime, String endTime) {
        List<StatisticsDaily> staList= dailyMapper.getDataByBetween(statrTime,endTime);



        List<String> xAxis= new ArrayList<>();

        List<List<Object>>  yAxis=  new ArrayList<>();

        yAxis.add(new ArrayList<>());// 首页访问量
        yAxis.add(new ArrayList<>());// 登录量
        yAxis.add(new ArrayList<>());// 注册量
        yAxis.add(new ArrayList<>());// 播放量
        yAxis.add(new ArrayList<>());// 视频成交额

        staList.forEach(item->{
            xAxis.add(item.getDateCalculated());// 时间坐标


            yAxis.get(0).add(item.getWebAccessNum());// 网站访问量
            yAxis.get(1).add(item.getLoginNum());// 登录量
            yAxis.get(2).add(item.getRegisterNum());// ...
            yAxis.get(3).add(item.getVideoViewNum());
            yAxis.get(4).add(item.getCoursePriceSum());
        });

        Map<String,Object> map= new HashMap<>();
        map.put("xAxis",xAxis);
        map.put("yAxis",yAxis);
        return map;
    }

    @Override
    public Map<String, Object> getDataByType(String type) {
        String statrTime=null;
        String endTime= DateUtils.formatDate(new Date(),0);
        switch (type){
            case "week":// 当前时间的前一周 包含今天是一周
                statrTime= DateUtils.formatDate(new Date(),-7);
                break;
            case "mouth":
                statrTime= DateUtils.formatDate(new Date(),-30);
                break;
            case "year":
                statrTime= DateUtils.formatDate(new Date(),-365);
                break;
            case "season":
                statrTime= DateUtils.formatDate(new Date(),-90);
                break;
            case "halfayear"://半年
                statrTime= DateUtils.formatDate(new Date(),-180);
                break;
            case "threeyear"://半年
                statrTime= DateUtils.formatDate(new Date(),-1095);
                break;
        }
        return getDataByBetween(statrTime,endTime);
    }

    @Override
    public String writeData(Map<String, Object> obj) {
        // 默认保存在C:根目录下
        String fileName="D:\\"+obj.get("title")+".xls";

        EasyExcel.write(fileName, DailyExcel.class).sheet(obj.get("title").toString()).doWrite(toData(obj));
        return fileName;
    }

    @Override
    @Transactional
    public void initData() {

        for (int i = 0; i <60 ; i++) {
// 新插入数据
            StatisticsDaily    statisticsDaily = new StatisticsDaily();
            statisticsDaily.setDateCalculated(DateUtils.formatDate(new Date(),i));
            statisticsDaily.setWebAccessNum(new Long(new Random().nextInt(100)));
            statisticsDaily.setLoginNum(new Long(new Random().nextInt(55)));
            statisticsDaily.setRegisterNum(new Long(new Random().nextInt(33)));
            statisticsDaily.setVideoViewNum(new Long(new Random().nextInt(300)));
            statisticsDaily.setCoursePriceSum(new Double(new Random().nextInt(2000)));

            this.baseMapper.insert(statisticsDaily);
        }






    }

    private List<DailyExcel> toData(Map<String, Object> obj) {
        List<DailyExcel> dailyExcels= new ArrayList<>();

        List<String> dateCalculateds= (List<String>) obj.get("xAxis");// 日期
        List<Object> yAxis= (List<Object>) obj.get("yAxis");


        List<Integer> data0= (List<Integer>) yAxis.get(0);
        List<Integer> data1= (List<Integer>) yAxis.get(1);
        List<Integer> data2= (List<Integer>) yAxis.get(2);
        List<Integer> data3= (List<Integer>) yAxis.get(3);
        List<Integer> data4= (List<Integer>) yAxis.get(4);

        for (int i = 0; i <dateCalculateds.size() ; i++) {
            DailyExcel dailyExcel= new DailyExcel();

            dailyExcel.setDateCalculated(dateCalculateds.get(i));
            dailyExcel.setWebAccessNum(data0.get(i)==null?0: new Long(data0.get(i)));
            dailyExcel.setLoginNum(data1.get(i)==null?0:new Long(data1.get(i)));
            dailyExcel.setRegisterNum(data2.get(i)==null?0:new Long(data2.get(i)));
            dailyExcel.setVideoViewNum(data3.get(i)==null?0:new Long(data3.get(i)));
            dailyExcel.setCoursePriceSum(data4.get(i)==null?0:new Double(data4.get(i)));
            dailyExcels.add(dailyExcel);

        }






        return dailyExcels;
    }


}
